package cn.janescott.framework.core.json.serializer;

import cn.janescott.framework.core.exception.MyException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

/**
 * 自定义异常 序列化类
 *
 * @author scott
 * @date 2019/2/25
 */
public class MyExceptionSerializer extends JsonSerializer<MyException> {

    public static final String ERROR_CODE = "errorCode";
    public static final String ERROR_MESSAGE = "errorMessage";
    public static final String ERROR_CAUSE = "errorCause";
    public static final String CLASS_NAME = "className";

    @Override
    public void serialize(MyException e, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField(ERROR_CODE, e.getErrorCode());
        jsonGenerator.writeStringField(ERROR_MESSAGE, e.getMessage());
        /* 序列化时，忽略掉异常栈帧信息 */
        /* jsonGenerator.writeObjectField(ERROR_CAUSE, e.getCause()); */
        /* 将异常的实际类型序列化 */
        jsonGenerator.writeStringField(CLASS_NAME, e.getClass().getName());
        jsonGenerator.writeEndObject();
    }

}
